const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const fs = require('fs');
const path = require('path');
const config = require('../config');
const logger = require('../utils/logger');

// 简化的WhatsApp客户端
let whatsappClient = null;
let qrCode = null;
let connectionStatus = 'disconnected';

/**
 * 简化的WhatsApp客户端初始化 - 使用与测试脚本相同的配置
 */
const initializeWhatsApp = async (userId = 'default') => {
  try {
    logger.info('开始初始化简化的WhatsApp客户端...');
    
    // 如果已经连接，直接返回
    if (whatsappClient && connectionStatus === 'connected') {
      logger.info('WhatsApp客户端已连接');
      return true;
    }
    
    // 清理旧客户端
    if (whatsappClient) {
      try {
        await whatsappClient.destroy();
      } catch (error) {
        logger.warn('清理旧客户端失败:', error.message);
      }
    }
    
    // 确保会话目录存在
    const sessionDir = './whatsapp-session';
    if (!fs.existsSync(sessionDir)) {
      fs.mkdirSync(sessionDir, { recursive: true });
    }
    
    // 使用简化的配置 - 与测试脚本完全相同
    whatsappClient = new Client({
      authStrategy: new LocalAuth({
        dataPath: sessionDir
      }),
      puppeteer: {
        headless: false,
        args: [
          '--no-sandbox',
          '--disable-setuid-sandbox',
          '--disable-dev-shm-usage',
          '--disable-gpu',
          '--disable-web-security'
        ]
      }
    });
    
    // 设置事件监听器
    whatsappClient.on('qr', (qr) => {
      logger.info('收到WhatsApp二维码');
      qrCode = qr;
      connectionStatus = 'connecting';
      
      // 向前端发送二维码
      if (global.io) {
        global.io.emit('whatsapp:qr', { qr });
      }
    });
    
    whatsappClient.on('authenticated', () => {
      logger.info('WhatsApp认证成功');
      qrCode = null;
    });
    
    whatsappClient.on('ready', () => {
      logger.info('WhatsApp客户端已准备就绪');
      connectionStatus = 'connected';
      qrCode = null;
      
      if (global.io) {
        global.io.emit('whatsapp:status', { status: 'connected', message: '已连接' });
      }
    });
    
    whatsappClient.on('auth_failure', (msg) => {
      logger.error('WhatsApp认证失败:', msg);
      connectionStatus = 'disconnected';
      
      if (global.io) {
        global.io.emit('whatsapp:status', { status: 'disconnected', message: '认证失败' });
      }
    });
    
    whatsappClient.on('disconnected', (reason) => {
      logger.info('WhatsApp已断开连接:', reason);
      connectionStatus = 'disconnected';
      qrCode = null;
      
      if (global.io) {
        global.io.emit('whatsapp:status', { status: 'disconnected', message: '已断开连接' });
      }
    });
    
    whatsappClient.on('error', (error) => {
      logger.error('WhatsApp客户端错误:', error);
    });
    
    // 初始化客户端
    logger.info('正在初始化WhatsApp客户端...');
    await whatsappClient.initialize();
    
    logger.info('WhatsApp客户端初始化完成');
    return true;
    
  } catch (error) {
    logger.error('WhatsApp客户端初始化失败:', error);
    connectionStatus = 'disconnected';
    return false;
  }
};

/**
 * 获取连接状态
 */
const getConnectionStatus = () => {
  return {
    status: connectionStatus,
    qrCode: connectionStatus === 'connecting' ? qrCode : null
  };
};

/**
 * 获取二维码
 */
const getQRCode = () => {
  return qrCode;
};

/**
 * 断开连接
 */
const disconnectWhatsApp = async () => {
  try {
    if (whatsappClient) {
      await whatsappClient.destroy();
      whatsappClient = null;
    }
    connectionStatus = 'disconnected';
    qrCode = null;
    
    return { success: true, message: '已断开连接' };
  } catch (error) {
    logger.error('断开WhatsApp连接失败:', error);
    return { success: false, message: '断开连接失败' };
  }
};

module.exports = {
  initializeWhatsApp,
  getConnectionStatus,
  getQRCode,
  disconnectWhatsApp
}; 